package com.app.couponsharelife.ui.main.home.local

import android.content.Intent
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout
import com.lcodecore.tkrefreshlayout.footer.LoadingView
import com.lcodecore.tkrefreshlayout.header.progresslayout.ProgressLayout
import com.app.couponsharelife.R
import com.app.couponsharelife.base.BaseActivity
import com.app.couponsharelife.data.bean.LifeShopPageBean
import com.app.couponsharelife.data.bean.PageTipBean
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.adapter.LocalShopsListAdapter
import com.app.couponsharelife.ui.listener.OnClickListener
import com.app.couponsharelife.ui.main.login.NewLoginActivity
import com.app.couponsharelife.ui.viewmodel.LocalViewModel
import com.app.couponsharelife.utils.AppUtils
import com.app.fuquan.data.bean.PageStatus
import kotlinx.android.synthetic.main.activity_local_shops_list.*
import java.util.*

class LocalShopsListActivity : BaseActivity() {

    override val viewLayoutId: Int get() = R.layout.activity_local_shops_list

    private var page = 1

    /**
     * 标记下拉刷新还是上拉加载
     */
    private var isRefresh = true

    private var keyword = ""

    private var classId = ""

    private var mViewModel: LocalViewModel? = null

    override fun initViews() {
        if (intent.getStringExtra("keyword") != null)
            keyword = intent.getStringExtra("keyword")

        if (intent.getStringExtra("classId") != null)
            classId = intent.getStringExtra("classId")

        ivBack.setOnClickListener { finish() }
        clSearchBar.setOnClickListener {
            startActivity(Intent(this, LocalShopsSearchActivity::class.java))
        }
        initRefreshLayout()
        initRecyclerView()
    }

    private fun initRefreshLayout() {
        mRefreshLayout.setFloatRefresh(true)
        mRefreshLayout.setAutoLoadMore(true)
        mRefreshLayout.setEnableLoadmore(true)
        mRefreshLayout.setEnableOverScroll(false)
        val header = ProgressLayout(this)
        header.setColorSchemeResources(R.color.act_main_bot_nav_select_text_color)
        mRefreshLayout.setHeaderView(header)
        mRefreshLayout.setBottomView(LoadingView(this))
        mRefreshLayout.setOnRefreshListener(object : RefreshListenerAdapter() {
            override fun onLoadMore(refreshLayout: TwinklingRefreshLayout?) {
                isRefresh = false
                loadData()
            }

            override fun onRefresh(refreshLayout: TwinklingRefreshLayout?) {
                isRefresh = true
                page = 1
                loadData()
            }
        })
    }

    private fun initRecyclerView() {
        mRecyclerView.layoutManager = LinearLayoutManager(this)
        mRecyclerView.adapter = LocalShopsListAdapter(arrayListOf(PageTipBean("", 0, 0)), object : OnClickListener {
            override fun click(arg1: Int, arg2: Any) {
                if (AppUtils.checkUserLogin()) {
                    val intent = Intent(this@LocalShopsListActivity, LocalShopDetailActivity::class.java)
                    intent.putExtra("shopId", (arg2 as LifeShopPageBean.RecordsBean).id)
                    startActivity(intent)
                } else startActivity(Intent(this@LocalShopsListActivity, NewLoginActivity::class.java))//startActivity(Intent(this@LocalShopsListActivity, LoginActivity::class.java))
            }
        })
    }

    override fun initViewModel() {
        if (mViewModel == null) mViewModel = ViewModelProviders.of(this).get(LocalViewModel::class.java)
        if (!mViewModel!!.getLifeShopPage()!!.hasObservers()) {
            mViewModel!!.getLifeShopPage()!!.observe(this, Observer {
                if (it == null) {
                    handleError(parseErrorDate("数据出错啦"))
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                    }
                    PageStatus.Error -> {
                        mViewModel!!.freshGetLifeShopPage(hashMapOf(), false)
                        handleError(parseErrorDate(it.error!!.message))
                    }
                    PageStatus.Empty -> {
                        mViewModel!!.freshGetLifeShopPage(hashMapOf(), false)
                        handleError(parseErrorDate("暂无数据"))
                    }
                    PageStatus.Content -> {
                        mViewModel!!.freshGetLifeShopPage(hashMapOf(), false)
                        if (it.data!!.code == 200 && it.data.data != null) {
                            handleContent(it.data.data!!)
                        } else {
                            handleError(parseErrorDate("请求失败"))
                        }
                    }
                }
            })
        }
        loadData()
    }

    private fun handleContent(data: LifeShopPageBean) {
        if (page == 1 && isRefresh) {
            mRefreshLayout.finishRefreshing()
        } else
            mRefreshLayout.finishLoadmore()
        if (data.records.isNotEmpty()) {
            page++
            (mRecyclerView.adapter as LocalShopsListAdapter).setData(data.records, page)
        } else {
            handleError(PageTipBean(if (page == 1) "暂无相关商家～" else "暂无更多商家", R.drawable.ic_no_shop, 1))
        }
    }

    private fun handleError(pageTipBean: PageTipBean) {
        if (page == 1) {
            if (isRefresh) mRefreshLayout.finishRefreshing() else mRefreshLayout.finishLoadmore()
            if ((mRecyclerView.adapter as LocalShopsListAdapter).list[0] is PageTipBean) {
                ((mRecyclerView.adapter as LocalShopsListAdapter).list[0] as PageTipBean).tip = pageTipBean.tip
                ((mRecyclerView.adapter as LocalShopsListAdapter).list[0] as PageTipBean).status = pageTipBean.status
                ((mRecyclerView.adapter as LocalShopsListAdapter).list[0] as PageTipBean).src = pageTipBean.src
                (mRecyclerView.adapter as LocalShopsListAdapter).notifyItemChanged(0)
            }
        } else {
            mRefreshLayout.finishLoadmore()
            showToastMsg(pageTipBean.tip)
        }
    }

    private fun loadData() {
        val map = HashMap<String, String>()
        if (keyword != "")
            map["keyword"] = keyword
        if (classId != "")
            map["classId"] = classId
        map["Longitude"] = AppUtils.getString("Longitude", Contacts.HZ_CENTER_LONGITUDE)
        map["Latitude"] = AppUtils.getString("Latitude", Contacts.HZ_CENTER_LATITUDE)
        map["distance"] = "10000"
        map["pageNo"] = page.toString()
        mViewModel?.freshGetLifeShopPage(map, true)
    }
}
